<?php

namespace App\Admin\Forms;

use App\Models\SitesInquiry;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use App\Models\StaffRecord as StaffRecordModel;

class DistributionSalesman extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input): object
    {
        //获取询盘单id
        $inquiry_id = $this->payload['id'] ?? null;
        // 获取业务员id，来自表单传参
        $staff_id = $input['name'] ?? null;
        //如果没有询盘单id或业务员id则返货参数错误
        if (!$inquiry_id || !$staff_id) {
            return $this->response()
                ->error('参数错误');
        }

        if (!SitesInquiry::where('id', $inquiry_id)->first()) {
            return $this->response()
                ->error('询盘单不存在');
        }
        $inquiry = new SitesInquiry();
        $inquiry
            ->where('id', $inquiry_id)
            ->update(['staff_id' => $staff_id,
                'inquiry_state' => 1]);
        return $this
            ->response()
            ->success('分配成功')
            ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->select('name', '业务员')->options(StaffRecordModel::all()->pluck('name', 'id'))->required();
        $this->text('business_note', '备注');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [
            'name' => '',
            'business_note' => '',
        ];
    }
}
